package controllers.user

import controllers.checkLogin
import play.api.Logging
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.json.Json
import play.api.mvc._
import services.kingdee.StockStoreNowService
import utiliy.OutFilterConfig

import javax.inject._
import scala.concurrent.ExecutionContext


/**
 * This controller creates an `Action` that demonstrates how to write
 * simple asynchronous code in a controller. It uses a timer to
 * asynchronously delay sending a response for 1 second.
 *
 * @param cc          standard controller components
 * @param actorSystem We need the `ActorSystem`'s `Scheduler` to
 *                    run code after a delay.
 * @param exec        We need an `ExecutionContext` to execute our
 *                    asynchronous code.  When rendering content, you should use Play's
 *                    default execution context, which is dependency injected.  If you are
 *                    using blocking operations, such as database or network access, then you should
 *                    use a different custom execution context that has a thread pool configured for
 *                    a blocking API.
 */
@Singleton
class KisStockStoreNowController @Inject()(cc: ControllerComponents,
                                           ssnow: StockStoreNowService,
                                           ofc: OutFilterConfig,
                                         )(implicit exec: ExecutionContext, parser: BodyParsers.Default)
  extends AbstractController(cc) with Logging {
  implicit val myCustomCharset = Codec.javaSupported("gb18030")

  def index = checkLogin(parser, exec) { implicit request =>
    val stock = ofc.getAllStockArr()
    Ok(views.html.users.kis_stockstore("金蝶即时库存", stock))
  }

  val ksnForm = Form(
    tuple(
      "stock" -> default(text, ("")),
      "item" -> default(text, ("")),
      "page" -> number,
      "limit" -> number
    )
  )

  def show = checkLogin(parser, exec) { implicit request =>
    val p = ksnForm.bindFromRequest().fold(
      formWithErrors => {
        logger.error("KisStockNowStore is application/badform")
        BadRequest(formWithErrors.toString)
        Tuple4("", "", 1, 10)
      },
      f => {
        println("KisStockNowStore is application/form")
        //implicit val formDataWrite = Json.writes[OutStockPostParameters]
        Tuple4(f._1, f._2, f._3, f._4)
      }
    )
    logger.info(s"KisStockNowStore form = ${p.toString()}")
    val data = ssnow.getNowtimeJson(p._1, p._2, p._3 - 1, p._4)
    Ok(Json.obj("code" -> 0, "message" -> "", "count" -> data._2, "data" -> data._1))
  }

  def test = Action {

    Ok("test")
  }

}
